package sdk.webview.fmc.com.fmcsdk.check.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.check.adapter.ImagePagerAdapter;
import sdk.webview.fmc.com.fmcsdk.check.adapter.ImageSelectAdapter;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.ImageSelectBean;
import sdk.webview.fmc.com.fmcsdk.check.dialog.CenterPopupWindow;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.ReadonlyWaterMeterView;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.ReadonlyWorkDetailView;
import sdk.webview.fmc.com.fmcsdk.check.persenter.ReadonlyWaterMeterPresenter;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;

public class ReadonlyWaterMeterActivity extends BaseActivity<ReadonlyWaterMeterView, ReadonlyWaterMeterPresenter> implements ReadonlyWorkDetailView {
    private TextView tv_value,tv_normal_range_value,tv_remake,
            tv_remake_font_count,tv_num,tv_water_meter,tv_water_meter_name;
    private RecyclerView rv_img;
    private ImageView iv_back;
    private LinearLayout ll_camera;
    private View view_line;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_readonly_water_meter;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        // 在 Activity 的 onCreate() 方法中设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.color_DC3C26)); // 设置状态栏颜色
        }

        initView();
        initData();
        initListener();
    }

    private void initListener() {
        iv_back.setOnClickListener(view -> finish());
    }

    private void initView(){
        tv_value = findViewById(R.id.tv_value);
        tv_normal_range_value = findViewById(R.id.tv_normal_range_value);
        tv_remake = findViewById(R.id.tv_remake);
        tv_remake_font_count = findViewById(R.id.tv_remake_font_count);
        tv_num = findViewById(R.id.tv_num);
        tv_water_meter = findViewById(R.id.tv_water_meter);
        rv_img = findViewById(R.id.rv_img);
        iv_back = findViewById(R.id.iv_back);
        tv_water_meter_name = findViewById(R.id.tv_water_meter_name);
        ll_camera = findViewById(R.id.ll_camera);
        view_line = findViewById(R.id.view_line);
    }

    @SuppressLint("SetTextI18n")
    private void initData(){
        String json = getIntent().getStringExtra("item");
        GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item = GsonUtil.GsonToBean(json, GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.class);
        tv_water_meter.setText(item.getMeterName());
        tv_water_meter_name.setText(item.getMeterName());
        tv_value.setText(item.getMeterRead());
        tv_normal_range_value.setText((null == item.getAlertLowLimit() ? "n" : item.getAlertLowLimit().stripTrailingZeros().toPlainString()) + "~" + (null == item.getAlertUpLimit() ? "n" : item.getAlertUpLimit().stripTrailingZeros().toPlainString()));
        tv_remake.setText(item.getRemark());
        tv_remake_font_count.setText((StringUtils.isEmpty(item.getRemark()) ? "0" : item.getRemark().length() + "") + "/100");
        tv_num.setText("(" + (null != item.getPictureUrls() ? item.getPictureUrls().size() : 1) + "/9" + ")");

        setRecycler(item);
    }


    private void setRecycler(GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO item) {

        List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO> pictureUrls = item.getPictureUrls();
        if (null != pictureUrls && !pictureUrls.isEmpty()){
            ll_camera.setVisibility(View.VISIBLE);
            view_line.setVisibility(View.VISIBLE);
        }else {
            ll_camera.setVisibility(View.GONE);
            view_line.setVisibility(View.GONE);
        }
        if (null != pictureUrls && !pictureUrls.isEmpty()) {
            List<ImageSelectBean> imageList = item.getImageList();
            for (GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO.PictureUrlsDTO pictureUrl : pictureUrls) {
                String url = pictureUrl.getUrl();
                if (!url.contains("http") && url.startsWith("/api")){
                    pictureUrl.setUrl(PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "")+url);
                }
//                if (pictureUrl.getUrl().contains("mp4")) {
//                    imageList.add(new ImageSelectBean(pictureUrl.getUrl(), 2));
//                } else {
//                    imageList.add(new ImageSelectBean(pictureUrl.getUrl(), 1));
//                }

            }
            item.setImageList(imageList);
        }

        List<ImageSelectBean> imageList = item.getImageList();
        for (int i = imageList.size()-1; i >= 0; i--) {
            if (imageList.get(i).getType() == 0){
                imageList.remove(i);
            }
        }
        rv_img.setLayoutManager(new GridLayoutManager(context, 5));
        KLog.e(GsonUtil.BeanToJson(imageList));
        ImageSelectAdapter imageSelectAdapter = new ImageSelectAdapter(imageList);
        rv_img.setAdapter(imageSelectAdapter);
        imageSelectAdapter.setOnItemChildClickListener((adapter, view, position) -> {
           if (view.getId() == R.id.iv_view) {
                ImageSelectBean imageSelectBean = (ImageSelectBean) adapter.getData().get(position);
                String url = imageSelectBean.getImg();
                if (imageSelectBean.getImg().contains("mp4")||imageSelectBean.getImg().contains("MP4")) {
                    if (null != url) {
                        if (!url.contains("http") && url.startsWith("/api")) {
                            String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.BASE_ADDRESS_URL, "");
                            url = baseUrl + url;
                            Intent intent = new Intent(context, VideoPlaybackActivity.class);
                            intent.putExtra("videoUrl", url);
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(context, VideoPlaybackActivity.class);
                            intent.putExtra("videoUrl", url);
                            startActivity(intent);
                        }
                    }
                } else {
                    showCenterPopupWindow(view, position, imageSelectAdapter.getData());
                }

            }
        });

    }
    private List<ImageSelectBean> recordList = new ArrayList<>();
    private void showCenterPopupWindow(View anchor, int position, List<ImageSelectBean> list) {
        ImageSelectBean selectBean=list.get(position);
        recordList.clear();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getImg().contains("mp4") || list.get(i).getImg().contains("MP4") || TextUtils.isEmpty(list.get(i).getImg())) {
                continue;
            }
            recordList.add(list.get(i));
        }
        CenterPopupWindow centerPopupWindow = new CenterPopupWindow(context, R.layout.dialog_center_img);
        ViewPager viewPager = centerPopupWindow.getContentView().findViewById(R.id.viewPager);
        ImageView iv_left = centerPopupWindow.getContentView().findViewById(R.id.iv_left);
        ImageView iv_right = centerPopupWindow.getContentView().findViewById(R.id.iv_right);
        iv_left.setOnClickListener(v -> {
            int currentItem = viewPager.getCurrentItem();
            if (currentItem > 0) {
                viewPager.setCurrentItem(currentItem - 1, true); // true for smooth scroll
            }
        });
        iv_right.setOnClickListener(v -> {
            int currentItem = viewPager.getCurrentItem();
            int totalItems = viewPager.getAdapter().getCount();
            if (currentItem < totalItems - 1) {
                viewPager.setCurrentItem(currentItem + 1, true); // true for smooth scroll
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (recordList.size() == 1) {
                    iv_left.setVisibility(View.GONE);
                    iv_right.setVisibility(View.GONE);
                } else {
                    if (i <= 0) {
                        iv_left.setVisibility(View.GONE);
                        iv_right.setVisibility(View.VISIBLE);
                    } else if (i >= recordList.size() - 1) {
                        iv_left.setVisibility(View.VISIBLE);
                        iv_right.setVisibility(View.GONE);
                    } else {
                        iv_left.setVisibility(View.VISIBLE);
                        iv_right.setVisibility(View.VISIBLE);
                    }
                }
            }


            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        centerPopupWindow.getContentView().findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                centerPopupWindow.dismiss();
            }
        });

        ImagePagerAdapter pagerAdapter = new ImagePagerAdapter(context, recordList);
        viewPager.setAdapter(pagerAdapter);

        int positionSelect = 0;
        for (int i = 0; i < recordList.size(); i++) {
            if (TextUtils.equals(selectBean.getImg(), recordList.get(i).getImg())) {
                positionSelect = i;
            }
        }
        if (positionSelect == 1) {
            iv_left.setVisibility(View.GONE);
            iv_right.setVisibility(View.VISIBLE);
        }
        if (recordList.size() == 1) {
            iv_left.setVisibility(View.GONE);
            iv_right.setVisibility(View.GONE);
        } else {
            if (positionSelect == 0) {
                iv_left.setVisibility(View.GONE);
                iv_right.setVisibility(View.VISIBLE);
            } else if (positionSelect == recordList.size() - 1) {
                iv_left.setVisibility(View.VISIBLE);
                iv_right.setVisibility(View.GONE);
            }else {
                iv_left.setVisibility(View.VISIBLE);
                iv_right.setVisibility(View.VISIBLE);
            }
        }


        viewPager.setCurrentItem(positionSelect);
        centerPopupWindow.show(anchor);
    }


    @Override
    protected ReadonlyWaterMeterPresenter createPresenter() {
        return new ReadonlyWaterMeterPresenter();
    }
}
